<template>
  <div id="patch">
    <ReturnPage />
    <div class="mt20">
      <!-- 查询表单 -->
      <el-form size="mini" :inline="true" class="demo-form-inline" ref="search">
        <el-form-item label="应用程序名称:">
          <el-input
            v-model="query.name"
            clearable
            placeholder="请输入应用程序名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="ml10" @click="getList"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="warning" class="ml10" @click="query.name = ''"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        class="mr10"
        size="mini"
        @click="
          dialogVisible = true;
          btnLoading = false;
        "
        >新增</el-button
      >
      <el-button type="warning" size="mini" @click="distribute(_, 1)"
        >批量分发</el-button
      >

      <!-- 列表 -->
      <div class="tp_box mt20">
        <el-table
          height="calc(100vh - 350px)"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="name" label="应用程序名称"> </el-table-column>
          <el-table-column prop="fileCount" label="包含文件数量">
          </el-table-column>
          <el-table-column
            prop="fileNames"
            label="包含文件名称"
            show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="version"
            label="版本号"
            show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ "v" + scope.row.version }}
            </template>
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="文件大小(M)"
            show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              (scope.row.fileSize / 1048576).toFixed(2) == "0.00"
                ? "0.01"
                : (scope.row.fileSize / 1048576).toFixed(2)
            }}</template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述"
            show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="operator" label="操作" width="210">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="warning"
                @click="distribute(scope.row, 0)"
                >分发</el-button
              >
              <el-button size="mini" type="danger" @click="delApp(scope.row.id)"
                >删除</el-button
              >
            </template></el-table-column
          >
        </el-table>
        <pagination
          v-show="tableData.length > 0"
          :total="tableData.length"
          :page.sync="query.pageNum"
          :limit.sync="query.pageSize"
          @pagination="getListData"
        />
      </div>
      <!--新增表单-->
      <el-dialog
        :title="'新增应用程序'"
        :visible.sync="dialogVisible"
        @close="resetForm('addForm')"
      >
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="应用程序名称" prop="name">
            <el-input
              v-model="addForm.name"
              placeholder="请输入应用程序名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="应用程序版本号" prop="version">
            <el-input
              v-model="addForm.version"
              placeholder="请输入版本号"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="addForm.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
              class="upload-demo"
              style="text-align: left"
              ref="upload"
              name="files"
              :action="upload.url"
              :headers="upload.headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :file-list="fileList"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              :multiple="true"
              :data="{
                name: addForm.name,
                version: addForm.version,
                description: addForm.description,
                hostId: addForm.hostId,
              }"
            >
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-plus"
              ></el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
            <!-- 文件列表 -->
            <el-table :data="fileList" style="width: 100%" size="mini">
              <el-table-column prop="name" label="文件名称"> </el-table-column>
              <el-table-column prop="size" label="文件大小">
                <template slot-scope="scope">{{
                  scope.row.size | filterSize
                }}</template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delFile(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('addForm')"
              :loading="btnLoading"
              >提交</el-button
            >
            <el-button @click="cancellation('addForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--编辑表单-->
      <el-dialog :title="'编辑应用程序'" :visible.sync="editdialogVisible">
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="应用程序名称" prop="name">
            <el-input
              v-model="editForm.name"
              placeholder="请输入应用程序名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="editForm.version"
              placeholder="请输入版本号"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="editForm.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
              class="upload-demo"
              style="text-align: left"
              ref="upload"
              name="files"
              :action="upload.url"
              :headers="upload.headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :file-list="fileList"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              :multiple="true"
              :data="{
                name: editForm.name,
                version: editForm.version,
                description: editForm.description,
                hostId: editForm.hostId,
                fileUrlList: editForm.fileUrlList,
                id: editForm.id,
              }"
            >
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-plus"
              ></el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>

            <!-- 文件列表 -->
            <el-table :data="editfileList" style="width: 100%" size="mini">
              <el-table-column prop="name" label="文件名称"> </el-table-column>
              <el-table-column prop="size" label="文件大小">
                <template slot-scope="scope">{{
                  scope.row.size | filterSize
                }}</template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delFile(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submit_editForm('editForm')"
              :loading="btnLoading"
              >提交</el-button
            >
            <el-button @click="editcancellation('editForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--分发应用程序-->
      <el-dialog
        :title="'分发应用程序'"
        :visible.sync="distributedialogVisible"
      >
        <el-form
          :model="sendForm"
          :rules="rules"
          ref="sendForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="远程主机IP" prop="hostIp">
            <el-input
              v-model="sendForm.hostIp"
              placeholder="请输入远程主机IP"
            ></el-input>
          </el-form-item>
          <el-form-item label="分发目录" prop="remoteFileDir">
            <el-input
              v-model="sendForm.remoteFileDir"
              placeholder="请输入分发目录"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="sendForm.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="sendForm.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="sendsubmitForm('sendForm')"
              >提交</el-button
            >
            <el-button @click="cancellationdialogVisible('sendForm')"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import {
  getAppList_Api, //获取应用程序列表
  delApp_Api, //删除应用程序
  getApp_Api, //根据id查询应用程序
  updateApp_Api, //修改应用程序
  dispenseApp_Api, //应用程序分发
} from "@/api/automated/host.js";
export default {
  data() {
    return {
      //提交按钮loading
      btnLoading: false,
      //上传文件参数
      upload: {
        // 是否显示弹出层（用户导入）
        // open: false,
        // 弹出层标题（用户导入）
        // title: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/automated/applicationprogram",
      },
      //文件上传
      fileList: [],
      //编辑获取的
      editfileList: [],
      //添加应用程序表单
      addForm: {
        name: null,
        version: null,
        description: null,
        hostId: null,
        hostIp: null,
      },
      //编辑表单
      editForm: {
        name: null,
        version: null,
        description: null,
        hostId: null,
        hostIp: null,
      },
      //分发表单
      sendForm: {
        hostIp: "", //主机ip
        remoteFileDir: "", //分发目录
        username: "", //用户名
        password: "", //密码
        dataId: null, //id
      },
      rules: {
        name: [
          { required: true, message: "请输入应用程序名称", trigger: "blur" },
        ],
        version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      //补丁或应用程序
      title: "",
      //分页
      query: {
        pageNum: 1,
        pageSize: 10,
        name: null, //
        hostId: null,
      },
      //列表数据
      tableData: [],
      dialogVisible: false, ////控制新增弹框
      editdialogVisible: false, //控制编辑弹框
      distributedialogVisible: false, //控制分发弹框
      multipleSelection: [], //多选
      singleOrMultiple: false, //true单个分发false多个分发
    };
  },
  methods: {
    //显示分发的弹窗
    distribute(row, type) {
      this.distributedialogVisible = true;
      if (type == 1) {
        //批量
        this.singleOrMultiple = false;
      } else {
        //单个
        this.sendForm.dataId = String(row.id);
        this.singleOrMultiple = true;
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //获取列表数据
    getList() {
      getAppList_Api(this.query).then((res) => {
        this.tableData = res.rows;
      });
    },
    //删除应用程序
    delApp(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          delApp_Api(id).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //确定提交
    submitForm(formName) {
      this.btnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 创建新的数据对象
          let formData = new FormData();
          // 将上传的文件放到数据对象中
          const fileName = [];
          this.fileList.forEach((file) => {
            formData.append("files", file.raw);
            fileName.push(file.name);
          });

          const nary = fileName.sort();
          for (let i = 0; i < nary.length; i++) {
            if (nary[i] == nary[i + 1]) {
              return this.$message.error("禁止上传相同的文件！");
            }
          }

          // 应用程序名
          formData.append("name", this.addForm.name);
          formData.append("version", this.addForm.version);
          formData.append("description", this.addForm.description);
          formData.append("hostId", this.addForm.hostId);
          formData.append("hostIp", this.addForm.hostIp);
          // 自定义上传
          this.uploadFile(formData)
            .then((response) => {
              this.btnLoading = false;
              this.$message.success("上传成功！");
              this.dialogVisible = false;
              this.getList();
              // if(response.code == 200){
              //   this.$refs.upload.clearFiles();
              //   this.msgSuccess('上传成功！');
              // }else{
              //   this.$message.error(response.msg);
              // }
            })
            .catch((error) => {
              this.$message.error("上传失败！");
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          this.btnLoading = false;
          return false;
        }
      });
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (this.dialogVisible) {
        this.resetForm("addForm");
        this.dialogVisible = false;
      } else if (this.editdialogVisible) {
        this.resetForm("editForm");
        this.editdialogVisible = false;
      }

      this.$refs.upload.clearFiles();
      this.$message.success("操作成功");
      this.dialogVisible = false;
      this.getList();
    },

    //编辑应用程序
    edit(row) {
      this.editfileList = [];
      getApp_Api(row.id).then((res) => {
        this.editForm = { ...res.data };
        let fileNames;
        if (res.data.fileNames) {
          fileNames = res.data.fileNames.split(",");
        }
        res.data.fileUrlList.forEach((item, index) => {
          this.editfileList.push({
            name: fileNames[index],
            size: res.data.fileSize,
            id: index,
          });
        });

        this.editdialogVisible = true;
        this.btnLoading = false;
      });
    },
    //提交编辑修改
    submit_editForm(formName) {
      this.btnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 创建新的数据对象
          let formData = new FormData();
          // 将上传的文件放到数据对象中
          const fileName = [];
          this.fileList.forEach((file) => {
            formData.append("files", file.raw);
            fileName.push(file.name);
          });

          // 应用程序名
          formData.append("name", this.editForm.name);
          formData.append("version", this.editForm.version);
          formData.append("description", this.editForm.description);
          formData.append("hostId", this.editForm.hostId);
          formData.append("hostIp", this.editForm.hostIp);
          formData.append("id", this.editForm.id);
          const fileName_edit = [];
          this.editfileList.forEach((item, index) => {
            // if (index < this.editfileList.length - this.fileList.length) {
            //   formData.append("fileNameList", item.name);
            // }
            formData.append("fileNameList", item.name);
            fileName_edit.push(item.name);
          });
          //判断文件是否重复
          const nary = fileName_edit.sort();
          for (let i = 0; i < nary.length; i++) {
            if (nary[i] == nary[i + 1]) {
              return this.$message.error("禁止上传相同的文件！");
            }
          }

          // 自定义上传
          this.uploadEdit_File(formData)
            .then((response) => {
              if (response.data.code == 200) {
                this.btnLoading = false;
                this.$message.success("操作成功！");
                this.editdialogVisible = false;
                this.getList();
                this.fileList = [];
                this.editfileList = [];
                // if(response.code == 200){
                // this.$refs.upload.clearFiles();
                //   this.msgSuccess('上传成功！');
                // }else{
                //   this.$message.error(response.msg);
                // }
              } else {
                this.$message.error("操作失败");
              }
            })
            .catch((error) => {
              this.$message.error("上传失败！");
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //编辑表单取消
    editcancellation() {
      this.editdialogVisible = false;
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
    },
    //关闭表单
    cancellation() {
      this.dialogVisible = false;
    },

    //提交分发
    sendsubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //判断是批量还是单个分发
          if (this.singleOrMultiple) {
            //单个
            dispenseApp_Api(this.sendForm).then((res) => {
              this.distributedialogVisible = false;
              this.$message.success(res.msg);
              this.getList();
            });
          } else {
            //批量 使用promise.all
            if (this.multipleSelection.length) {
              const itemIds = this.multipleSelection.map((item) =>
                item.id.toString()
              );
              const tempArr = itemIds.map((item) => {
                return dispenseApp_Api({ ...this.sendForm, dataId: item });
              });
              Promise.all(tempArr)
                .then((res) => {
                  this.$message.success(res[0].msg);
                  this.getList();
                  this.distributedialogVisible = false;
                })
                .catch((error) => {
                  this.$message.error("操作失败");
                });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancellationdialogVisible() {
      this.distributedialogVisible = false;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    //选取的文件改变
    handleChange(file, fileList) {
      // this.editfileList.push(file);
      this.btnLoading = false;
      this.fileList = fileList;
      if (this.editdialogVisible) {
        //追加进表格
        this.editfileList.push(file);
      }
    },
    //关闭新增弹窗
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
    },
    //删除文件
    delFile(row) {
      if (row.uid) {
        //删本地上传的
        this.fileList.splice(
          this.fileList.findIndex((item) => item.uid == row.uid),
          1
        );
        //删除表格展示的
        this.editfileList.splice(
          this.fileList.findIndex((item) => item.uid == row.uid),
          1
        );
      } else {
        //删接口返回的
        this.editfileList.splice(
          this.editfileList.findIndex((item) => item.id == row.id),
          1
        );
        // this.editForm.fileUrlList.splice(row.id, 1);
      }
    },
    // 封装的上传请求
    uploadFile(params) {
      return axios.post(
        process.env.VUE_APP_BASE_API + `/automated/applicationprogram`,
        params,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + getToken(),
          },
        }
      );
    },
    // 封装的编辑上传请求
    uploadEdit_File(params) {
      return axios.put(
        process.env.VUE_APP_BASE_API + `/automated/applicationprogram`,
        params,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + getToken(),
          },
        }
      );
    },
  },
  filters: {
    filterSize(val) {
      const units = ["Bytes", "KB", "MB", "GB", "TB"];
      let index = 0;
      let size = val;
      // 将文件大小逐步除以1024，直到达到最适合的单位

      if (size >= 1024) {
        while (size >= 1024 && index < units.length - 1) {
          size /= 1024;
          index++;
        }
        return size.toFixed(2) + " " + units[index];
      } else {
        return size + " " + "Bytes";
      }
      // 保留两位小数
    },
  },
  created() {
    this.query.hostId = this.$route.query.hostid;
    this.addForm.hostId = this.$route.query.hostid; //主机id
    this.addForm.hostIp = this.$route.query.hostIp; //主机ip
    // this.sendForm.hostIp = this.$route.query.hostIp.split(":")[0];
    this.getList();
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  text-align: right;
}
</style>